package com.wans.ssq.service.Impl;

import com.wans.common.constans.CustomExceptionEnum;
import com.wans.common.exception.CustomRunningException;
import com.wans.common.result.ResponseResult;
import com.wans.model.lottery.ssq.dos.SSQ;
import com.wans.model.lottery.ssq.dos.SSQUser;
import com.wans.model.lottery.ssq.dtos.ListUserRecordDTO;
import com.wans.model.lottery.ssq.dtos.UserRecordDTO;
import com.wans.ssq.mapper.SSQMapper;
import com.wans.ssq.mapper.UserSSQMapper;
import com.wans.ssq.service.UserSSQService;
import com.wans.utils.string.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class UserSSQServiceImpl implements UserSSQService {

    @Autowired
    private SSQMapper ssqMapper;

    @Autowired
    private UserSSQMapper userSSQMapper;

    /**
     * 保存用户的双色球记录
     *
     * @param userRecord 用户记录
     * @return 保存结果
     */
    @Override
    public ResponseResult<Void> saveUserRecord(UserRecordDTO userRecord, String userId) {

        // 获取数据库中最新期次
        SSQ newHistory = ssqMapper.getNewHistoryCode();
        if (Integer.parseInt(userRecord.getCode()) > Integer.parseInt(newHistory.getNextCode()))
            // 期次比数据库中最新期次的下期期次还大
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_CODE_ERROR);

        // 是下期期次
        if (userRecord.getCode().equals(newHistory.getNextCode())) {
            // 拿取 DO 类
            SSQUser ssqUser = userRecord.toSSQUser(UUID.randomUUID().toString().replace("-", ""), userId);
            // 设置固定值
            ssqUser.setBonusPrize("0");
            ssqUser.setPrizeLevel("0");

            // 添加进数据库
            Integer inserted = userSSQMapper.saveUserRecord(ssqUser);

            if (inserted == null || inserted == 0)
                // 插入数据失败
                throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_INSERT_ERROR);

            return ResponseResult.success();
        }

        // 根据期次查询 中奖数据
        SSQ history = ssqMapper.getHistoryByCode(userRecord.getCode());
        // 校验期次
        if (Integer.parseInt(userRecord.getCode()) <= Integer.parseInt(history.getNextCode()))
            // 该期次大概率存在 因为小于等于下期期次
            if (ssqMapper.getHistoryByCode(userRecord.getCode()) == null)
                // 说明该期期次不存在
                throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_CODE_ERROR);

        // 拿取 DO 类
        SSQUser ssqUser = userRecord.toSSQUser(UUID.randomUUID().toString().replace("-", ""), userId);

        // 计算奖金
        ssqUser.calculatePrize(history);

        // 添加进数据库
        Integer inserted = userSSQMapper.saveUserRecord(ssqUser);

        if (inserted == null || inserted == 0)
            // 插入数据失败
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_INSERT_ERROR);

        return ResponseResult.success();
    }

    /**
     * 删除指定记录
     *
     * @param id     记录 id
     * @param userId 用户 id
     * @return 操作结果
     */
    @Override
    public ResponseResult<Void> deleteUserRecord(String id, String userId) {

        // 删除记录
        Integer inserted = userSSQMapper.deleteUserRecord(id, userId);

        if (inserted == null || inserted == 0)
            // 删除失败
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_DELETE_ERROR);

        return ResponseResult.success();
    }

    /**
     * 修改某一条记录
     *
     * @param userRecord 修改记录
     * @param userId     用户 id
     * @return 修改结果
     */
    @Override
    public ResponseResult<Void> updateUserRecord(UserRecordDTO userRecord, String userId) {

        // 校验
        if (StringUtils.isContainEmpty(userRecord.getId()))
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_DATA_ERROR);

        // 根据 id userId 查询
        SSQUser record = userSSQMapper.getUserRecord(userRecord.getId(), userId);

        if (record == null || StringUtils.isContainEmpty(record.getId()))
            // 假数据 - 数据库中没有这个
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_DATA_ERROR);


        // 获取数据库中最新期次
        SSQ newHistory = ssqMapper.getNewHistoryCode();
        if (Integer.parseInt(userRecord.getCode()) > Integer.parseInt(newHistory.getNextCode()))
            // 期次比数据库中最新期次的下期期次还大
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_CODE_ERROR);

        // 是下期期次
        if (userRecord.getCode().equals(newHistory.getNextCode())) {
            // 拿取 DO 类
            SSQUser ssqUser = userRecord.toSSQUser();
            ssqUser.setId(userRecord.getId());
            ssqUser.setUserId(userId);
            // 设置固定值
            ssqUser.setBonusPrize("0");
            ssqUser.setPrizeLevel("0");

            // 添加进数据库
            Integer inserted = userSSQMapper.updateUserRecord(ssqUser);

            if (inserted == null || inserted == 0)
                // 插入数据失败
                throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_INSERT_ERROR);

            return ResponseResult.success();
        }

        // 根据期次查询 中奖数据
        SSQ history = ssqMapper.getHistoryByCode(userRecord.getCode());
        // 校验期次
        if (Integer.parseInt(userRecord.getCode()) <= Integer.parseInt(history.getNextCode()))
            // 该期次大概率存在 因为小于等于下期期次
            if (ssqMapper.getHistoryByCode(userRecord.getCode()) == null)
                // 说明该期期次不存在
                throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_CODE_ERROR);

        // 修改数据
        SSQUser ssqUser = userRecord.toSSQUser();
        ssqUser.setId(userRecord.getId());
        ssqUser.setUserId(userId);


        // 计算奖金
        ssqUser.calculatePrize(history);

        // 更新进数据库
        Integer inserted = userSSQMapper.updateUserRecord(ssqUser);

        if (inserted == null || inserted == 0)
            // 插入数据失败
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_UPDATE_ERROR);

        return ResponseResult.success();
    }

    /**
     * 获取数据列表
     *
     * @param queryParam 请求参数、分页等
     * @param userId     用户 id
     * @return 数据列表
     */
    @Override
    public ResponseResult<List<SSQUser>> listUserRecords(ListUserRecordDTO queryParam, String userId) {

        //TODO 校验数据

        // 计算
        queryParam.calculatePagination();

        // 查询
        List<SSQUser> records = userSSQMapper.listUserRecords(queryParam);

        if (records == null || records.isEmpty())
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_SELECT_ERROR);

        return ResponseResult.success(records);
    }

    /**
     * 获取数据列表 - 未进行计算奖金的数据记录
     *
     * @return 数据列表
     */
    @Override
    public ResponseResult<List<SSQUser>> listUserRecords() {
        return ResponseResult.success(userSSQMapper.listUpdateRecords());
    }

    /**
     * 修改某一条记录
     *
     * @param userRecord 修改记录
     * @return 修改结果
     */
    @Override
    public ResponseResult<Void> updateRecord(SSQUser userRecord) {

        // 更新进数据库
        Integer inserted = userSSQMapper.updateUserRecord(userRecord);

        if (inserted == null || inserted == 0)
            // 插入数据失败
            throw new CustomRunningException(CustomExceptionEnum.USER_SSQ_UPDATE_ERROR);

        return ResponseResult.success();
    }
}
